package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.AddressBookDao;
import cn.yunyichina.provider.base.entity.AddressBook;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.framework.utils.UUIDUtil;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by JoeZ on 2016/9/19.
 */
@Service
public class AddressBookServiceImpl extends BaseSelectService {

    private static final Logger logger = LoggerFactory.getLogger(AddressBookServiceImpl.class);

    @Autowired
    private AddressBookDao addressBookDao;

    /**
     * 根据条件查询地址簿信息(支持分页)
     * @param data
     * @interface yyt.base.address.book.list
     * @return
     */
    public Response listAddressBook(String data, String sessionId) {

        logger.info("【base模块-根据条件查询地址簿】开始, 请求="+data,",sessionId=" + sessionId);
        Response response = new Response();

        try {
            AddressBook addressBookRequest = JsonUtils.parseObject(data, AddressBook.class);
            PageInfo pageInfo = JsonUtils.parseObject(data, PageInfo.class);

            if(addressBookRequest != null){
                if(StringUtils.isBlank(addressBookRequest.getOpenId())){
                    response.setResultCodeAndMessage("1002", "open_id不能为空");
                    logger.info("【base模块-根据条件查询地址簿】结束, 返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }

                //根据条件查询用户的地址簿信息，按使用时间倒叙排序
                List<String> orderColumns = new ArrayList<String>();
                orderColumns.add("use_time");

                List<AddressBook> list = new ArrayList<>();
                boolean isPage = false;
                if(pageInfo.getPageNum() != null && pageInfo.getPageSize() != null){
                    list = addressBookDao.select(addressBookRequest, orderColumns, false, pageInfo);
                    isPage = true;
                }else{
                    list = addressBookDao.select(addressBookRequest, orderColumns, false);
                }

                if(list != null && list.size() > 0){
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("list",list);
                    //如果有分页要求，则返回分页的信息
                    if(isPage){
                        long count = addressBookDao.selectCount(addressBookRequest);
                        pageInfo.setTotal(count);
                        pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
                        map.put("page_info",pageInfo);
                    }
                    response.setResult(JsonUtils.toJsonString(map));
                    response.setResultCodeAndMessage("0", "查询成功");
                }else{
                    response.setResultCodeAndMessage("1001", "查无结果");
                }
            }else{
                response.setResultCodeAndMessage("1002", "入参有误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("1999", e.getMessage());
        }

        logger.info("【base模块-根据条件查询地址簿】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;
    }

    /**
     * 保存地址簿信息
     * @param data
     * @interface yyt.base.address.book.save
     * @return
     */
    public Response saveAddressBook(String data, String sessionId) {

        logger.info("【base模块-保存地址簿信息】开始, 请求="+data,",sessionId=" + sessionId);
        Response response = new Response();

        try {
            AddressBook addressBookRequest = JsonUtils.parseObject(data, AddressBook.class);

            if(addressBookRequest != null){
                if(StringUtils.isBlank(addressBookRequest.getId())){
                    //id空，操作为新增
                    if(StringUtils.isBlank(addressBookRequest.getOpenId())){
                        response.setResultCodeAndMessage("1002", "open_id不能为空");
                        logger.info("【base模块-根据条件查询地址簿】结束, 返回结果=" + JsonUtils.toJsonString(response));
                        return response;
                    }
                    if(addressBookRequest.getType() == null || addressBookRequest.getType().intValue() == 0){
                        response.setResultCodeAndMessage("1002", "type不能为空");
                        logger.info("【base模块-根据条件查询地址簿】结束, 返回结果=" + JsonUtils.toJsonString(response));
                        return response;
                    }
                    addressBookRequest.setId(UUIDUtil.get32UUID());
                    addressBookRequest.setCreatedTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    addressBookDao.insert(addressBookRequest);
                    response.setResultCodeAndMessageAndResult("0", "新增成功",JsonUtils.toJsonString(addressBookRequest));
                }else{
                    //id空，操作为更新
                    AddressBook addressBook = addressBookDao.selectById(addressBookRequest.getId());
                    if(addressBook != null){
                        addressBookRequest.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        addressBookDao.update(addressBookRequest);
                        response.setResultCodeAndMessage("0", "更新成功");
                    }else{
                        response.setResultCodeAndMessage("1001", "无此记录");
                    }
                }
            }else{
                response.setResultCodeAndMessage("1002", "入参有误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("1999", e.getMessage());
        }

        logger.info("【base模块-保存地址簿信息】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;
    }

    /**
     * 删除地址簿信息
     * @param data
     * @interface yyt.base.address.book.delete
     * @return
     */
    public Response deleteAddressBook(String data, String sessionId) {

        logger.info("【base模块-删除地址簿信息】开始, 请求="+data,",sessionId=" + sessionId);
        Response response = new Response();

        try {
            AddressBook addressBookRequest = JsonUtils.parseObject(data, AddressBook.class);

            if(addressBookRequest != null){
                if(StringUtils.isBlank(addressBookRequest.getId())){
                    response.setResultCodeAndMessage("1002", "id不能为空");
                    logger.info("【base模块-根据条件查询地址簿】结束, 返回结果=" + JsonUtils.toJsonString(response));
                    return response;
                }

                AddressBook addressBook = addressBookDao.selectById(addressBookRequest.getId());
                if(addressBook != null){
                    addressBookDao.delete(addressBookRequest);
                    response.setResultCodeAndMessage("0", "删除成功");
                }else{
                    response.setResultCodeAndMessage("1001", "无此记录");
                }
            }else{
                response.setResultCodeAndMessage("1002", "入参有误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("1999", e.getMessage());
        }

        logger.info("【base模块-删除地址簿信息】结束, 返回结果=" + JsonUtils.toJsonString(response));
        return response;
    }

}
